package cn.bone.springcloud.controller;

import cn.bone.springcloud.service.IPaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@Slf4j
public class OrderController {

    @Resource
    private IPaymentService paymentService;

    @RequestMapping("/order/success/{id}")
    public String paymentInfoSuccess(@PathVariable("id") Integer id){
        String result = paymentService.paymentInfoSuccess(id);
        log.info("paymentInfoSuccess result:{}",result);
        return result;
    }

    //在服务调用方配置Hystrix，不能定义在接口上。只能在调用接口的方法上定义（本例子中是在controller的方法上）
    @HystrixCommand(fallbackMethod = "paymentInfoTimeoutHandle",
            commandProperties = {
                    @HystrixProperty(
                            name = "execution.isolation.thread.timeoutInMilliseconds",
                            value = "5000"
                    )
            }
    )
    @RequestMapping("/order/timeout/{id}")
    public String paymentInfoTimeout(@PathVariable("id") Integer id){
        String result = paymentService.paymentInfoTimeout(id);
        log.info("paymentInfoTimeout result:{}",result);
        return result;
    }


    private String paymentInfoTimeoutHandle(Integer id){
        StringBuilder builder = new StringBuilder();
        builder.append("当前线程：");
        builder.append(Thread.currentThread().getName());
        builder.append("\t");
        builder.append("order timeout handle");
        builder.append("\t");
        builder.append("id：");
        builder.append(id);

        return builder.toString();
    }
}
